<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧模块列表 -->
      <el-col :span="6">
        <el-card>
          <div class="module-header">
            <el-button type="primary" @click="showAddModuleDialog">
              <el-icon>
                <Plus />
              </el-icon>新增
            </el-button>
          </div>
          <el-scrollbar class="template-scroll">
            <div v-for="template in moduleList" :key="template.moduleConfigId" class="template-item"
              :class="[activeModule.moduleConfigId == template.moduleConfigId ? 'active' : '']"
              @click="selectModule(template)">
              <div class="template-name">{{ template.kpiModule }}</div>
              <div>
                <el-button type="text" @click="showEditModuleDialog(template)">编辑</el-button>
                <el-button type="text" @click="handleDeleteModule(template)">删除</el-button>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧指标配置 -->
      <el-col :span="18">
        <el-card>
          <div class="module-header">
            <span>{{ activeModule.kpiModule || '请选择模块' }} - 指标配置</span>
            <el-button type="primary" size="small" @click="showAddIndicatorDialog"
              :disabled="!activeModule.moduleConfigId">
              <el-icon>
                <Plus />
              </el-icon>添加指标
            </el-button>
          </div>

          <el-table :data="kpiList" border class="kpi-table" v-loading="loading" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
            <el-table-column prop="kpiName" label="指标名称" align="center" />
            <el-table-column prop="kpiType" label="指标类型" align="center" />
            <el-table-column prop="unit" label="单位" align="center" />
            <el-table-column label="操作" align="center" width="180">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="handleRemoveKpi(row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑模块对话框 -->
    <el-dialog v-model="moduleDialogVisible" :title="moduleDialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="currentModule" label-width="120px" :rules="moduleRules" ref="moduleFormRef">
        <el-form-item label="模块名称" prop="kpiModule">
          <el-input v-model="currentModule.kpiModule" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="是否展示" prop="isDisplayed">
          <el-switch v-model="currentModule.isDisplayed" :active-value="1" :inactive-value="0" active-text="是"
            inactive-text="否" />
        </el-form-item>
        <el-form-item label="展示顺序" prop="displayOrder">
          <el-input-number v-model="currentModule.displayOrder" :min="1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="moduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmModule">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加指标对话框 -->
    <el-dialog v-model="indicatorDialogVisible" title="添加指标到模块" width="70%" :close-on-click-modal="false">
      <div class="dialog-content">
        <el-input v-model="kpiSearch" placeholder="搜索指标名称" clearable class="search-input" @clear="handleKpiSearch"
          @keyup.enter="handleKpiSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-table :data="filteredKpiOptions" border style="width: 100%" height="400px"
          @selection-change="handleSelectionChange" v-loading="kpiLoading">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="kpiName" label="指标名称"  />
          <el-table-column prop="kpiType" label="指标类型" />
          <el-table-column prop="unit" label="单位" width="100" />
        </el-table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetSelection">重置</el-button>
          <el-button @click="indicatorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddKpi">添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import {
  getKpiModuleList,
  addKpiModule,
  updateKpiModule,
  deleteKpiModule,
  getKpiModuleDetail,
  getKpiListByModule,
  getAllKpiList,
  addKpiToModule,
  removeKpiFromModule
} from '@/api/prod_operate/sys_setting/kpi/module'

// 加载状态
const loading = ref(false)
const kpiLoading = ref(false)

// 模块列表数据
const moduleList = ref([])

// 当前选中的模块
const activeModule = ref({
  moduleConfigId: '',
  kpiModule: '',
  isDisplayed: 0,
  displayOrder: 1
})

// 指标列表数据
const kpiList = ref([])

// 全部指标选项
const kpiOptions = ref([])

// 查询参数
const queryParams = reactive({
  moduleConfigId: '',
  kpiName: ''
})

// 搜索关键词
const kpiSearch = ref('')

// 当前选中的指标
const selectedKpis = ref([])

// 当前操作的模块
const currentModule = reactive({
  moduleConfigId: '',
  kpiModule: '',
  isDisplayed: 1,
  displayOrder: 1
})

// 对话框控制
const moduleDialogVisible = ref(false)
const moduleDialogTitle = ref('新增模块')
const indicatorDialogVisible = ref(false)

// 表单引用
const moduleFormRef = ref(null)

// 表单验证规则
const moduleRules = reactive({
  kpiModule: [
    { required: true, message: '请输入模块名称', trigger: 'blur' }
  ],
  isDisplayed: [
    { required: true, message: '请选择是否展示', trigger: 'change' }
  ],
  displayOrder: [
    { required: true, message: '请输入展示顺序', trigger: 'blur' }
  ]
})

// 筛选后的指标选项
const filteredKpiOptions = computed(() => {
  if (!kpiSearch.value) return kpiOptions.value
  return kpiOptions.value.filter(item =>
    item.kpiName.toLowerCase().includes(kpiSearch.value.toLowerCase())
  )
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true
    await fetchModuleList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取模块列表
const fetchModuleList = async () => {
  try {
    const res = await getKpiModuleList()
    moduleList.value = res.rows

    // 默认选中第一个模块
    if (moduleList.value.length > 0) {
      await selectModule(moduleList.value[0])
    }
  } catch (error) {
    console.error('获取模块列表失败:', error)
    ElMessage.error('获取模块列表失败')
  }
}

// 获取模块详情
const fetchModuleDetail = async (moduleConfigId) => {
  try {
    const res = await getKpiModuleDetail(moduleConfigId)
    Object.assign(activeModule.value, res.data)
  } catch (error) {
    console.error('获取模块详情失败:', error)
    ElMessage.error('获取模块详情失败')
  }
}

// 获取模块下的指标列表
const fetchKpiList = async (moduleConfigId) => {
  try {
    loading.value = true
    const res = await getKpiListByModule( moduleConfigId )
    kpiList.value = res.data
  } catch (error) {
    console.error('获取指标列表失败:', error)
    ElMessage.error('获取指标列表失败')
  } finally {
    loading.value = false
  }
}

// 获取全部指标列表
const fetchAllKpiList = async () => {
  try {
    kpiLoading.value = true
    queryParams.moduleConfigId = activeModule.value.moduleConfigId
    const res = await getAllKpiList(queryParams)
    kpiOptions.value = res.data
  } catch (error) {
    console.error('获取全部指标列表失败:', error)
    ElMessage.error('获取全部指标列表失败')
  } finally {
    kpiLoading.value = false
  }
}

// 选择模块
const selectModule = async (module) => {
  Object.assign(activeModule.value, module)
  await fetchKpiList(module.moduleConfigId)
}

// 显示新增模块对话框
const showAddModuleDialog = () => {
  moduleDialogTitle.value = '新增模块'
  resetCurrentModule()
  moduleDialogVisible.value = true
}

// 显示编辑模块对话框
const showEditModuleDialog = (module) => {
  moduleDialogTitle.value = '编辑模块'
  Object.assign(currentModule, module)
  moduleDialogVisible.value = true
}

// 重置当前模块
const resetCurrentModule = () => {
  currentModule.moduleConfigId = ''
  currentModule.kpiModule = ''
  currentModule.isDisplayed = 1
  currentModule.displayOrder = 1
}

// 确认模块操作
const confirmModule = async () => {
  try {
    await moduleFormRef.value.validate()

    if (moduleDialogTitle.value === '新增模块') {
      await addKpiModule(currentModule)
      ElMessage.success('新增模块成功')
    } else {
      await updateKpiModule(currentModule)
      ElMessage.success('修改模块成功')
    }

    moduleDialogVisible.value = false
    await fetchModuleList()
  } catch (error) {
    console.error('保存模块失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除模块
const handleDeleteModule = (module) => {
  ElMessageBox.confirm(`确认删除模块 "${module.kpiModule}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteKpiModule(module.moduleConfigId)
      ElMessage.success('删除成功')
      await fetchModuleList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 显示添加指标对话框
const showAddIndicatorDialog = async () => {
  await fetchAllKpiList()
  indicatorDialogVisible.value = true
}

// 处理指标搜索
const handleKpiSearch = () => {
  fetchAllKpiList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedKpis.value = selection
}

// 重置选择
const resetSelection = () => {
  selectedKpis.value = []
  kpiSearch.value = ''
}

// 确认添加指标
const confirmAddKpi = async () => {
  try {
    if (selectedKpis.value.length === 0) {
      ElMessage.warning('请至少选择一个指标')
      return
    }

    const kpiConfigIds = selectedKpis.value.map(item => item.kpiConfigId)
    await addKpiToModule({
      moduleConfigId: activeModule.value.moduleConfigId,
      kpiConfigIds
    })

    ElMessage.success('添加指标成功')
    indicatorDialogVisible.value = false
    resetSelection()
    await fetchKpiList(activeModule.value.moduleConfigId)
  } catch (error) {
    console.error('添加指标失败:', error)
    ElMessage.error('添加指标失败')
  }
}

// 处理移除指标
const handleRemoveKpi = (row) => {
  ElMessageBox.confirm(`确认从模块中移除指标 "${row.kpiName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await removeKpiFromModule(row.id)
      ElMessage.success('移除成功')
      await fetchKpiList(activeModule.value.moduleConfigId)
    } catch (error) {
      console.error('移除失败:', error)
      ElMessage.error('移除失败')
    }
  }).catch(() => {
    // 取消移除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.module-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.module-name {
  font-weight: bold;
}

.module-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.kpi-table {
  margin-top: 20px;
}

.search-input {
  margin-bottom: 20px;
}

.dialog-content {
  padding: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.template-scroll {
  height: 850px;
  overflow-y: auto;
}

.template-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.template-item:hover {
  border-color: #409eff;
}

.template-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.template-name {
  font-weight: bold;
  margin-bottom: 5px;
}
</style>